package com.ruoyi.basic.service.impl;

import java.util.Arrays;
import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.basic.domain.BasicPost;
import com.ruoyi.basic.domain.BasicUser;
import com.ruoyi.basic.mapper.BasicUserMapper;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.basic.mapper.BasicTrainMapper;
import com.ruoyi.basic.domain.BasicTrain;
import com.ruoyi.basic.service.IBasicTrainService;
import com.ruoyi.common.core.text.Convert;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 培训经历Service业务层处理
 * 
 * @author ruoyi
 * @date 2021-08-23
 */
@Service
public class BasicTrainServiceImpl extends ServiceImpl<BasicTrainMapper, BasicTrain> implements IBasicTrainService
{

    @Autowired
    private BasicUserMapper userMapper;

    /**
     * 查询培训经历
     * 
     * @param trainId 培训经历主键
     * @return 培训经历
     */
    @Override
    public BasicTrain selectBasicTrainByTrainId(Long trainId)
    {
        return baseMapper.selectBasicTrainByTrainId(trainId);
    }

    /**
     * 查询培训经历
     *
     * @param trainIds 培训经历主键
     * @return 培训经历
     */
    @Override
    public List<BasicTrain> selectBasicTrainByTrainIds(String trainIds)
    {
        LambdaQueryWrapper<BasicTrain> queryWrapper = new LambdaQueryWrapper<BasicTrain>();
        queryWrapper.in(BasicTrain::getTrainId, Convert.toLongArray(trainIds));
        return baseMapper.selectList(queryWrapper);
    }

    /**
     * 查询培训经历列表
     * 
     * @param basicTrain 培训经历
     * @return 培训经历
     */
    @Override
    public List<BasicTrain> selectBasicTrainList(BasicTrain basicTrain)
    {
        return baseMapper.selectBasicTrainList(basicTrain);
    }

    /**
     * 新增培训经历
     * 
     * @param basicTrain 培训经历
     * @return 结果
     */
    @Override
    public int insertBasicTrain(BasicTrain basicTrain)
    {
        basicTrain.setCreateTime(DateUtils.getNowDate());
        return baseMapper.insert(basicTrain);
    }

    /**
     * 修改培训经历
     * 
     * @param basicTrain 培训经历
     * @return 结果
     */
    @Override
    public int updateBasicTrain(BasicTrain basicTrain)
    {
        basicTrain.setUpdateTime(DateUtils.getNowDate());
        return baseMapper.updateById(basicTrain);
    }

    /**
     * 批量删除培训经历
     * 
     * @param trainIds 需要删除的培训经历主键
     * @return 结果
     */
    @Override
    public int deleteBasicTrainByTrainIds(String trainIds)
    {
        return baseMapper.deleteBatchIds(Arrays.asList(Convert.toLongArray(trainIds)));
    }

    /**
     * 删除培训经历信息
     * 
     * @param trainId 培训经历主键
     * @return 结果
     */
    @Override
    public int deleteBasicTrainByTrainId(Long trainId)
    {
        return baseMapper.deleteById(trainId);
    }

    /**
     * 导入员工培训经历
     *
     * @param trainList 员工培训经历列表
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    public String importTrain(List<BasicTrain> trainList, Boolean isUpdateSupport, String operName)
    {
        if (StringUtils.isNull(trainList) || trainList.size() == 0)
        {
            throw new ServiceException("导入员工培训经历数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        int row = 2;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (BasicTrain train : trainList)
        {
            try
            {
                if(StringUtils.isEmpty(train.getTrainName())){
                    continue;
                }
                //获取用户信息
                BasicUser user = userMapper.selectOne(new LambdaQueryWrapper<BasicUser>()
                        .eq(BasicUser::getIdCard, train.getIdCard()).last("limit 1"));
                if(StringUtils.isNotNull(user)) {
                    train.setUserId(user.getId());
                }else{
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、第 " + row + "行导入失败，员工 " + train.getUserName() + " 不存在");
                    continue;
                }

                BasicTrain info = baseMapper.selectOne(new LambdaQueryWrapper<BasicTrain>()
                        .eq(BasicTrain::getTrainName, train.getTrainName())
                        .eq(BasicTrain::getUserId, train.getUserId()).last("limit 1"));
                if (StringUtils.isNull(info))
                {
                    train.setCreateBy(operName);
                    this.insertBasicTrain(train);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、员工 " + train.getUserName() + "培训经历 " + train.getTrainName() + " 导入成功");
                }
                else if (isUpdateSupport)
                {
                    train.setTrainId(info.getTrainId());
                    train.setUpdateBy(operName);
                    this.updateBasicTrain(train);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、员工 " + train.getUserName() + "培训经历 " + train.getTrainName() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、员工 " + train.getUserName() + "培训经历 " + train.getTrainName() + " 已存在");
                }
                train.setCreateBy(operName);
                this.insertBasicTrain(train);
                successNum++;
                successMsg.append("<br/>" + successNum + "、员工 " + train.getUserName() + " 培训经历导入成功");
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、员工 " + train.getUserName() + " 培训经历导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
            finally {
                row++;
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
}
